<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC Play Stream</title>
    <style>
        #video-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, 300px);
            grid-auto-rows: 300px;
            width: 300px;
            height: 300px;
        }

        video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>

<body>
    <div id="video-grid"><video id="video1" autoplay preload muted></video></div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io.connect();

        const configuration = { iceServers: [{ urls: 'stun:118.25.18.233:3478' }] };
        const peerConnection = new RTCPeerConnection(configuration);

        peerConnection.onicecandidate = (event) => {
            console.log('onicecandidate', event);

            if (event.candidate) {
                socket.emit('ice-candidate', event.candidate);
            }
        };

        const video = document.createElement('video1');
        video.addEventListener('loadedmetadata', () => {
            video.play();
        });

        peerConnection.ontrack = (event) => {
            console.log('ontrack', event);
            video.srcObject = event.streams[0];
        };

        socket.on('offer', (offer) => {
            console.log('offer', offer);
            peerConnection.setRemoteDescription(new RTCSessionDescription(offer))
                .then(() => {
                    return peerConnection.createAnswer();
                })
                .then((answer) => {
                    return peerConnection.setLocalDescription(answer);
                })
                .then(() => {
                    socket.emit('answer', peerConnection.localDescription);
                })
                .catch((error) => {
                    console.error('Error handling offer:', error);
                });
        });

        socket.on('ice-candidate', (candidate) => {
            console.log('ice-candidate', candidate);
            peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
                .catch((error) => {
                    console.error('Error adding ice candidate:', error);
                });
        });
    </script>
</body>

</html>